/*jslint browser: true*/
/*global $, jQuery, alert, window*/
window.view = {
    "paper_name": function (name_string) {
        "use strict";
        if (name_string) {
            $("#paper_name").val(name_string);
        } else {
            return window.trim($("#paper_name").val());
        }
    },
    "major_id": function (id_value) {
        "use strict";
        //set and get
        if (id_value) {
            $("#major_select option[value=" + id_value + "]")[0].selected = true;
        } else {
            return parseInt($("#major_select").val(), 10);
        }
    },
    "time_limit": function (minite_num) {
        "use strict";
        //set and get
        if (minite_num) {
            $("#time_limit").val(minite_num);
        } else {
            return parseInt($("#time_limit").val(), 10);
        }
    },
    "score": function (score_int) {
        "use strict";
        //set and get
        if (score_int) {
            $("#score").val(score_int);
        } else {
            return parseInt($("#score").val(), 10);
        }
    },
    "pass_score": function (score_int) {
        "use strict";
        if (score_int) {
            $("#pass_score").val(score_int);
        } else {
            return parseInt($("#pass_score").val(), 10);
        }
    },
    "a1_count": function (count_num) {
        "use strict";
        if (count_num || count_num === 0) {
            $("#a1_count").val(count_num);
        } else {
            return parseInt($("#a1_count").val(), 10);
        }
    },
    "a1_each_score": function (score_num) {
        "use strict";
        if (score_num) {
            $("#a1_each_score").val(score_num);
        } else {
            return parseFloat($("#a1_each_score").val()) || 0;
        }
    },
    "a1_href": function (href_str) {
        "use strict";
        if (href_str) {
            $("#a1_edit").attr("href", href_str);
        } else {
            return $("#a1_edit").attr("href");
        }
    },
    "a2_count": function (count_num) {
        "use strict";
        if (count_num || count_num === 0) {
            $("#a2_count").val(count_num);
        } else {
            return parseInt($("#a2_count").val(), 10);
        }
    },
    "a2_each_score": function (score_num) {
        "use strict";
        if (score_num) {
            $("#a2_each_score").val(score_num);
        } else {
            return parseFloat($("#a2_each_score").val()) || 0;
        }
    },
    "a2_href": function (href_str) {
        "use strict";
        if (href_str) {
            $("#a2_edit").attr("href", href_str);
        } else {
            return $("#a2_edit").attr("href");
        }
    },
    "b1_count": function (count_num) {
        "use strict";
        if (count_num || count_num === 0) {
            $("#b1_count").val(count_num);
        } else {
            return parseInt($("#b1_count").val(), 10);
        }
    },
    "b1_each_score": function (score_num) {
        "use strict";
        if (score_num) {
            $("#b1_each_score").val(score_num);
        } else {
            return parseFloat($("#b1_each_score").val()) || 0;
        }
    },
    "b1_href": function (href_str) {
        "use strict";
        if (href_str) {
            $("#b1_edit").attr("href", href_str);
        } else {
            return $("#b1_edit").attr("href");
        }
    },
    "a3_count": function (count_num) {
        "use strict";
        if (count_num || count_num === 0) {
            $("#a3_count").val(count_num);
        } else {
            return parseInt($("#a3_count").val(), 10);
        }
    },
    "a3_each_score": function (score_num) {
        "use strict";
        if (score_num) {
            $("#a3_each_score").val(score_num);
        } else {
            return parseFloat($("#a3_each_score").val()) || 0;
        }
    },
    "a3_href": function (href_str) {
        "use strict";
        if (href_str) {
            $("#a3_edit").attr("href", href_str);
        } else {
            return $("#a3_edit").attr("href");
        }
    },
    "a4_count": function (count_num) {
        "use strict";
        if (count_num || count_num === 0) {
            $("#a4_count").val(count_num);
        } else {
            return parseInt($("#a4_count").val(), 10);
        }
    },
    "a4_each_score": function (score_num) {
        "use strict";
        if (score_num) {
            $("#a4_each_score").val(score_num);
        } else {
            return parseFloat($("#a4_each_score").val()) || 0;
        }
    },
    "a4_href": function (href_str) {
        "use strict";
        if (href_str) {
            $("#a4_edit").attr("href", href_str);
        } else {
            return $("#a4_edit").attr("href");
        }
    },
    "A1_choice": function (choice_num) {
        "use strict";
        if (choice_num || choice_num === 0) {
            $("#a1_num").html(choice_num);
        }
        return parseInt(window.trim($("#a1_num").html()), 10);
    },
    "A2_choice": function (choice_num) {
        "use strict";
        if (choice_num || choice_num === 0) {
            $("#a2_num").html(choice_num);
        }
        return parseInt(window.trim($("#a2_num").html()), 10);
    },
    "B1_choice": function (choice_num) {
        "use strict";
        if (choice_num || choice_num === 0) {
            $("#b1_num").html(choice_num);
        }
        return parseInt(window.trim($("#b1_num").html()), 10);
    },
    "A3_choice": function (choice_num) {
        "use strict";
        if (choice_num || choice_num === 0) {
            $("#a3_num").html(choice_num);
        }
        return parseInt(window.trim($("#a3_num").html()), 10);
    },
    "A4_choice": function (choice_num) {
        "use strict";
        if (choice_num || choice_num === 0) {
            $("#a4_num").html(choice_num);
        }
        return parseInt(window.trim($("#a4_num").html()), 10);
    }
};

window.sync = {
    major_data_select : function () {
        "use strict";
        var major_list = window.fetchData(window.storage("/major/"), window.format.major),
            index,
            length = major_list.length,
            major_item,
            option_list = [];
        for (index = 0; index < length; index = index + 1) {
            major_item = major_list[index];
            option_list.push('<option value="{id}">{name}</option>'.format({
                id: major_item.id,
                name: major_item.name
            }));
        }
        $(option_list.join("")).appendTo("#major_select");
    },
    paper_data_html: function () {
        "use strict";
        var paper_key = window.paper_key,
            paper_url = "/manager/paper/{paper_id}/".format({
                paper_id: window.paper_id
            }),
            paper_data = window.fetchData(window.storage(paper_key), window.format.paper)[0];
        window.view.major_id(paper_data.major_id);
        window.view.time_limit(paper_data.time_limit);
        window.view.score(paper_data.score);
        window.view.pass_score(paper_data.pass_score);
        window.view.paper_name(paper_data.name);
        window.view.a1_count(paper_data.count_A1);
        window.view.a2_count(paper_data.count_A2);
        window.view.b1_count(paper_data.count_B1);
        window.view.a3_count(paper_data.count_A3);
        window.view.a4_count(paper_data.count_A4);
        window.view.A1_choice(paper_data.choice_A1);
        window.view.A2_choice(paper_data.choice_A2);
        window.view.B1_choice(paper_data.choice_B1);
        window.view.A3_choice(paper_data.choice_A3);
        window.view.A4_choice(paper_data.choice_A4);
        window.view.a1_each_score(paper_data.score_A1);
        window.view.a2_each_score(paper_data.score_A2);
        window.view.b1_each_score(paper_data.score_B1);
        window.view.a3_each_score(paper_data.score_A3);
        window.view.a4_each_score(paper_data.score_A4);
        window.view.a1_href(paper_url + "A1/");
        window.view.a2_href(paper_url + "A2/");
        window.view.b1_href(paper_url + "B1/");
        window.view.a3_href(paper_url + "A3/");
        window.view.a4_href(paper_url + "A4/");
    },
    "paper_detail_entry": function () {
        "use strict";
        var paper_key = window.paper_key,
            paper_data = window.fetchData(window.storage(paper_key), window.format.paper)[0];
        if (paper_data.is_active) {
            $("#paper_detail").show();
            $("create_detail").val("重新生成试卷");
        }
    }
};

function fetchPaperData() {
    "use strict";
    var paper_data = {
        "major_id": window.view.major_id(),
        "category_num": 2,
        "time_limit": window.view.time_limit(),
        "score": window.view.score(),
        "pass_score": window.view.pass_score(),
        "name": window.view.paper_name(),
        "count_A1": window.view.a1_count(),
        "count_A2": window.view.a2_count(),
        "count_B1": window.view.b1_count(),
        "count_A3": window.view.a3_count(),
        "count_A4": window.view.a4_count(),
        "score_A1": window.view.a1_each_score(),
        "score_A2": window.view.a2_each_score(),
        "score_B1": window.view.b1_each_score(),
        "score_A3": window.view.a3_each_score(),
        "score_A4": window.view.a4_each_score()
    };
    return paper_data;
}

window.init = {
    "global_var": function () {
        "use strict";
        var pathname = location.pathname,
            created_reg = new RegExp('^/manager/paper/([0-9]+)/$'),
            reg_result_list = created_reg.exec(pathname),
            is_paper_edit,
            paper_id;
        if (reg_result_list) {
            window.is_paper_edit = true;
            window.paper_id = reg_result_list[1];
            window.paper_key = "/paper/{paper_id}/".format({paper_id: window.paper_id});
        }
    },
    "major_select": function () {
        "use strict";
        //major list
        window.storage("/major/");
        window.sync.major_data_select();
    },
    "paper_created_html": function () {
        "use strict";
        if (window.is_paper_edit) {
            $(".paper_created").removeClass("paper_created");
        }
    },
    "paper_data_html": function () {
        "use strict";
        if (window.is_paper_edit) {
            window.sync.paper_data_html();
            window.sync.paper_detail_entry();
        }
    },
    "addEventListener": function () {
        "use strict";
        $("#save_paper").click(function () {
            window.loading();
            if (window.is_paper_edit) {
                window.listener.editPaper();
            } else {
                window.listener.createPaper();
            }
        });
        $("#create_detail").click(window.listener.create_detail);
        //question list
        $("#a1_edit").click(function () {
            window.open(window.view.a1_href(), "_blank");
        });
        $("#a2_edit").click(function () {
            window.open(window.view.a2_href(), "_blank");
        });
        $("#b1_edit").click(function () {
            window.open(window.view.b1_href(), "_blank");
        });
        $("#a3_edit").click(function () {
            window.open(window.view.a3_href(), "_blank");
        });
        $("#a4_edit").click(function () {
            window.open(window.view.a4_href(), "_blank");
        });
        $("#paper_detail").click(window.listener.show_paper_detail);
        //hide loading icon
        window.hideLoading();
        
    }
};
window.init_func_list = ["global_var",
                         "major_select",
                         "paper_created_html",
                         "paper_data_html",
                         "addEventListener"];

window.listener = {
    "create_detail": function () {
        "use strict";
        if (!window.listener.varify_create_detail()) {
            return false;
        }
        window.loading();
        $.ajax({
            url:  window.paper_key,
            type: "PUT",
            dataType: "json",
            async: true,
            data: JSON.stringify({is_active: true}),
            success: function (result, status) {
                window.storage(window.paper_key, result.data);
                window.sync.paper_detail_entry();
                window.hideLoading();
            }
        });
    },
    "varify_create_detail": function () {
        "use strict";
        var paper_data = window.storage(window.paper_key)[0],
            total_score = paper_data.count_A1 * paper_data.score_A1 +
                        paper_data.count_A2 * paper_data.score_A2 +
                        paper_data.count_B1 * paper_data.score_B1 +
                        paper_data.count_A3 * paper_data.score_A3 +
                        paper_data.count_A4 * paper_data.score_A4;
        paper_data.choice_A1 = window.view.A1_choice();
        paper_data.choice_A2 = window.view.A2_choice();
        paper_data.choice_B1 = window.view.B1_choice();
        paper_data.choice_A3 = window.view.A3_choice();
        paper_data.choice_A4 = window.view.A4_choice();
        if (paper_data.choice_A1 !== paper_data.count_A1) {
            window.alert("题型A1，设计应该有" + paper_data.count_A1　+
                         "道题，实际有" + paper_data.choice_A1 +
                         "道题。\n请修改后再次操作。");
            return false;
        } else if (paper_data.choice_A2 !== paper_data.count_A2) {
            window.alert("题型A2，设计应该有" + paper_data.count_A2　+
                         "道题，实际有" + paper_data.choice_A2 +
                         "道题。\n请修改后再次操作。");
            return false;
        } else if (paper_data.choice_B1 !== paper_data.count_B1) {
            window.alert("题型B1，设计应该有" + paper_data.count_B1　+
                         "道题，实际有" + paper_data.choice_B1 +
                         "道题。\n请修改后再次操作。");
            return false;
        } else if (paper_data.choice_A3 !== paper_data.count_A3) {
            window.alert("题型A3，设计应该有" + paper_data.count_A3　+
                         "道题，实际有" + paper_data.choice_A3 +
                         "。\n请修改后再次操作。");
            return false;
        } else if (paper_data.choice_A4 !== paper_data.count_A4) {
            window.alert("题型A3，设计有" + paper_data.count_A4　+
                         "道题，实际有" + paper_data.choice_A4 +
                         "道题。\n请修改后再次操作。");
            return false;
        } else if (paper_data.paper_score !== total_score) {
            window.alert("试卷设计总分有" + paper_data.paper_score　+
                         "，实际总分是" + total_score +
                         "。\n请修改后再次操作。");
            return false;
        } else if (paper_data.paper_pass_score !== paper_data.paper_score * 0.6) {
            if (!window.confirm("试卷设计及格分数是" + paper_data.paper_pass_score　+
                         "，不是总分" + paper_data.paper_score +
                        "的60%。\n确认继续吗？")) {
                return false;
            }
        } else if (!window.confirm("确认生成试卷内容吗？\n\n" +
                                   "生成试卷之后，试卷内容不能再更改。\n" +
                                   "即使编辑试题内容，试卷内容也不会随之改变。\n\n" +
                                   "试卷名称：" +　paper_data.paper_name + "\n" +
                                   "考试时间：" + paper_data.paper_time_limit + "分钟。")) {
            return false;
        }
        return true;
        
    },
    "editPaper": function () {
        "use strict";
        var item,
            paper_data = fetchPaperData(),
            save_paper_key =  "/paper/{paper_id}/".format({paper_id: window.paper_id}),
            save_data = window.storage(save_paper_key)[0],
            update_data = {};
        for (item in paper_data) {
            if (paper_data.hasOwnProperty(item)) {
                if (paper_data[item] !== save_data[item]) {
                    update_data[item] = paper_data[item];
                }
            }
        }
        $.ajax({
            url:  save_paper_key,
            type: "PUT",
            dataType: "json",
            async: true,
            data: JSON.stringify(update_data),
            success: function (result, status) {
                var paper_list = result.data;
                window.storage(save_paper_key, paper_list);
                window.hideLoading();
            }
        });
    },
    "createPaper": function () {
        "use strict";
        var paper_data = fetchPaperData();
        $.ajax({
            url:  "/paper/",
            type: "POST",
            dataType: "json",
            async: true,
            data: JSON.stringify(paper_data),
            success: function (result, status) {
                var paper_list = result.data,
                    paper_id = window.fetchData(paper_list, window.format.paper)[0].id,
                    save_paper_key = "/paper/{paper_id}/".format({paper_id: paper_id}),
                    paper_url = "/manager/paper/{paper_id}/".format({paper_id: paper_id});
                window.storage(save_paper_key, paper_list);
                window.location.assign(paper_url);
            }
        });
    },
    "show_paper_detail": function () {
        "use strict";
        window.open("/manager/paper/{id}/detail/".format({
            id: window.paper_id
        }));
    }
};